package com.kollway.imageselector.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.media.Image;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.OnScanCompletedListener;
import android.net.Uri;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcel;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.kollway.imageselector.AlbumBitmapCacheHelper;
import com.kollway.imageselector.AlbumBitmapCacheHelper.ILoadImageCallback;
import com.kollway.imageselector.R;
import com.kollway.imageselector.R.color;
import com.kollway.imageselector.R.drawable;
import com.kollway.imageselector.R.id;
import com.kollway.imageselector.R.layout;
import com.kollway.imageselector.R.string;
import com.kollway.imageselector.util.CommonUtils;
import com.kollway.imageselector.util.ParcelUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import static com.kollway.imageselector.activity.PicturePreviewActivity.getSmartBarHeight;

/**
 * Created by chenxiabin on 04/11/2016.
 * 选择图片页面
 */

public class PictureSelectorActivity extends Activity {

    public static final int SP_PICTURE_SELECTOR_REQUEST = 1010;
    public static final String SP_PICTURE_SELECTOR_DATA = "SP_PICTURE_SELECTOR_DATA";
    public static final String SP_PICTURE_SELECTOR_PREVIEW = "SP_PICTURE_SELECTOR_PREVIEW";
    public static final String SP_PICTURE_SELECTOR_MAX = "SP_PICTURE_SELECTOR_MAX";
    public static final String SP_PICTURE_SELECTOR_TAKE_PHOTO = "SP_PICTURE_SELECTOR_TAKE_PHOTO";

    private View mWholeView;
    private RelativeLayout mToolbarTop;
    private RelativeLayout mToolbarBottom;
    private GridView mGridView;
    private Button mBtnSend;
    private PicTypeBtn mPicType;
    private PreviewBtn mPreviewBtn;
    private View mCatalogView;
    private ListView mCatalogListView;
    private List<PicItem> mAllItemList;
    private Map<String, List<PicItem>> mItemMap;
    private List<String> mCatalogList;
    private String mCurrentCatalog = "";
    private String savePath;
    private boolean mSendOrigin = false;
    private int perWidth;

    private GridViewAdapter gridAdapter;
    private CatalogAdapter catalogAdapter;

    //可配置参数
    private boolean usePreview;//是否打开图片预览
    private boolean isTakePhoto;//是否设置第一项为相机
    private int selectMax;//可选择图片的最大数量

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(1);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ko_picsel_activity);
        mWholeView = findViewById(R.id.whole_layout);
        mToolbarTop = (RelativeLayout) findViewById(id.toolbar_top);
        mToolbarBottom = (RelativeLayout) findViewById(id.toolbar_bottom);

        if (savedInstanceState != null) {
            PicItemHolder.itemList = savedInstanceState.getParcelableArrayList("ItemList");
            PicItemHolder.selectList = savedInstanceState.getStringArrayList("SelectList");
            savePath = savedInstanceState.getParcelable("TakePicturePath");
        }
        if (PicItemHolder.selectList == null) {
            PicItemHolder.selectList = new ArrayList<>();
        }
        AlbumBitmapCacheHelper.getInstance().init(this);
        usePreview = getIntent().getBooleanExtra(SP_PICTURE_SELECTOR_PREVIEW, false);
        isTakePhoto = getIntent().getBooleanExtra(SP_PICTURE_SELECTOR_TAKE_PHOTO, true);
        selectMax = getIntent().getIntExtra(SP_PICTURE_SELECTOR_MAX, 9);

        mGridView = (GridView) findViewById(id.gridlist);

        //初始化返回按钮
        ImageView mBtnBack = (ImageButton) findViewById(id.back);
        mBtnBack.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                finish();
            }
        });
        mBtnSend = (Button) findViewById(id.send);

        //图片文件夹
        mPicType = (PicTypeBtn) findViewById(id.pic_type);
        mPicType.init(this);
        mPicType.setEnabled(false);

        //初始化预览按钮
        mPreviewBtn = (PreviewBtn) findViewById(id.preview);
        mPreviewBtn.init(this);
        mPreviewBtn.setEnabled(false);
        mPreviewBtn.setVisibility(usePreview ? View.VISIBLE : View.GONE);

        mCatalogView = findViewById(id.catalog_window);
        mCatalogListView = (ListView) findViewById(id.catalog_listview);
        initView();

        int result;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            mWholeView.setSystemUiVisibility(1024);
            result = getSmartBarHeight(this);
            if (result > 0) {
                LinearLayout.LayoutParams resourceId = (LinearLayout.LayoutParams) mToolbarBottom.getLayoutParams();
                resourceId.setMargins(0, 0, 0, result);
                mToolbarBottom.setLayoutParams(resourceId);
            }
        }

        result = 0;
        int resourceId1 = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId1 > 0) {
            result = getResources().getDimensionPixelSize(resourceId1);
        }

        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(mToolbarTop.getLayoutParams());
        lp.setMargins(0, result, 0, 0);
        mToolbarTop.setLayoutParams(lp);
    }

    @TargetApi(Build.VERSION_CODES.M)
    private void initView() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int checkPermission = checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
            if (checkPermission != 0) {
                if (shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE)) {
                    requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 100);
                } else {
                    (new Builder(this)).setMessage("您需要在设置里打开读取内存卡权限。").setPositiveButton("确认", new android.content.DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 100);
                        }
                    }).setNegativeButton("取消", null).create().show();
                }
                return;
            }
        }
        updatePictureItems();
        mGridView.setAdapter(gridAdapter = new GridViewAdapter());
        mBtnSend.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Intent data = new Intent();
                data.putExtra("sendOrigin", mSendOrigin);
                data.putExtra(SP_PICTURE_SELECTOR_DATA, PicItemHolder.selectList);
                setResult(RESULT_OK, data);
                finish();
            }
        });
        mPicType.setEnabled(true);
        mPicType.setTextColor(getResources().getColor(color.ko_picsel_toolbar_send_text_normal));
        mPicType.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                mCatalogView.setVisibility(mCatalogView.getVisibility() != View.VISIBLE ? View.VISIBLE : View.GONE);
            }
        });
        mPreviewBtn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                getPreviewPicList();

                Intent intent = new Intent(PictureSelectorActivity.this, PicturePreviewActivity.class);
                intent.putExtra(SP_PICTURE_SELECTOR_MAX, selectMax);
                intent.putExtra("sendOrigin", mSendOrigin);
                startActivityForResult(intent, 0);
            }
        });
        mCatalogView.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == 1 && mCatalogView.getVisibility() == View.VISIBLE) {
                    mCatalogView.setVisibility(View.GONE);
                }
                return true;
            }
        });
        mCatalogListView.setAdapter(catalogAdapter = new CatalogAdapter());
        mCatalogListView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String catalog;
                if (position == 0) {
                    catalog = "";
                } else {
                    catalog = mCatalogList.get(position - 1);
                }

                if (catalog.equals(mCurrentCatalog)) {
                    mCatalogView.setVisibility(View.GONE);
                } else {
                    mCurrentCatalog = catalog;
                    TextView textView = (TextView) view.findViewById(R.id.name);
                    mPicType.setText(textView.getText().toString());
                    mCatalogView.setVisibility(View.GONE);
                    catalogAdapter.notifyDataSetChanged();
                    gridAdapter.notifyDataSetChanged();
                }
            }
        });

        //计算每一项的宽度
        WindowManager wm = getWindowManager();
        Display display = wm.getDefaultDisplay();

        Point point = new Point();
        display.getSize(point);
        int width = point.x;
        perWidth = (width - CommonUtils.dip2px(this, 4.0F)) / 3;
    }

    //获取预览的图片列表
    private void getPreviewPicList() {
        PicItemHolder.itemList = new ArrayList<>();
        for (Object key : mItemMap.keySet()) {

            for (Object o : ((List) mItemMap.get(key))) {
                PicItem item = (PicItem) o;
                if (PicItemHolder.selectList.contains(item.uri)) {
                    PicItemHolder.itemList.add(item);
                }
            }
        }

        //按照选择的顺序排列图片
        ArrayList<PicItem> list = new ArrayList<>();
        for (String path : PicItemHolder.selectList) {
            for (PicItem item : PicItemHolder.itemList) {
                if (path.equals(item.uri)) {
                    list.add(item);
                }
            }
        }
        PicItemHolder.itemList = list;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        updateToolbar();
        if (resultCode != 0) {
            if (resultCode == 1) {//在预览点击完成回来的
                setResult(RESULT_OK, data);
                finish();
            } else {
                switch (requestCode) {
                    case 0://预览回来的
                        mSendOrigin = data.getBooleanExtra("sendOrigin", false);

                        gridAdapter.notifyDataSetChanged();
                        catalogAdapter.notifyDataSetChanged();
                        updateToolbar();
                        break;
                    case 1://拍照回来的
                        if (!TextUtils.isEmpty(savePath)) {
                            getPreviewPicList();

                            PicItem item = new PicItem();
                            item.uri = savePath;
                            PicItemHolder.itemList.add(item);
                            PicItemHolder.selectList.add(item.uri);//拍照后图片默认选中

                            Intent intent = new Intent(this, PicturePreviewActivity.class);
                            intent.putExtra(SP_PICTURE_SELECTOR_MAX, selectMax);
                            intent.putExtra("index", PicItemHolder.itemList.size() - 1);
                            startActivityForResult(intent, 0);

                            MediaScannerConnection.scanFile(this, new String[]{savePath}, null, new OnScanCompletedListener() {
                                public void onScanCompleted(String path, Uri uri) {
                                    updatePictureItems();
                                }
                            });
                        }
                }
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == 4 && mCatalogView != null && mCatalogView.getVisibility() == View.VISIBLE) {
            mCatalogView.setVisibility(View.GONE);
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    @TargetApi(Build.VERSION_CODES.M)
    protected void requestCamera() {
        if (getTotalSelectedNum() == selectMax) {
            Toast.makeText(getApplicationContext(),
                    getResources().getString(string.ko_picsel_selected_max,
                            new Object[]{Integer.valueOf(selectMax)}), Toast.LENGTH_SHORT).show();
            return;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int checkPermission = checkSelfPermission(Manifest.permission.CAMERA);
            if (checkPermission != 0) {
                if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {
                    requestPermissions(new String[]{Manifest.permission.CAMERA}, 100);
                } else {
                    (new Builder(PictureSelectorActivity.this)).setMessage("您需要在设置里打开相机权限。").setPositiveButton("确认", new android.content.DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            requestPermissions(new String[]{Manifest.permission.CAMERA}, 100);
                        }
                    }).setNegativeButton("取消", null).create().show();
                }
                return;
            }
        }

        File storageDir = getExternalCacheDir();
        String imageFileName = "take_photo";
        File photoFile = null;
        try {
            photoFile = File.createTempFile(
                    imageFileName,  // prefix
                    ".jpg",         // suffix
                    storageDir      // directory
            );
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (photoFile == null || !photoFile.exists()){
            Toast.makeText(this, "创建临时文件失败，请重试", Toast.LENGTH_SHORT).show();
            return;
        }

        savePath = photoFile.getAbsolutePath();
        Uri mTakePictureUri;

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            mTakePictureUri = Uri.fromFile(photoFile);
        } else {
            String packageName = getPackageName();
            mTakePictureUri = FileProvider.getUriForFile(this,
                    packageName + ".fileprovider",
                    photoFile);
        }

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mTakePictureUri);
        startActivityForResult(intent, 1);
    }

    private void updatePictureItems() {
        String[] projection = new String[]{MediaStore.MediaColumns.DATA, MediaStore.MediaColumns.DATE_ADDED};
        String orderBy = MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC";
        Cursor cursor = getContentResolver().query(Media.EXTERNAL_CONTENT_URI, projection, null, null, orderBy);

        mAllItemList = new ArrayList<>();
        mCatalogList = new ArrayList<>();
        mItemMap = new ArrayMap<>();
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                do {
                    PicItem item = new PicItem();
                    item.uri = cursor.getString(0);
                    mAllItemList.add(item);
                    int last = item.uri.lastIndexOf("/");
                    String catalog;
                    if (last == 0) {
                        catalog = "/";
                    } else {
                        int itemList = item.uri.lastIndexOf("/", last - 1);
                        catalog = item.uri.substring(itemList + 1, last);
                    }

                    if (mItemMap.containsKey(catalog)) {
                        mItemMap.get(catalog).add(item);
                    } else {
                        ArrayList<PicItem> itemList1 = new ArrayList<>();
                        itemList1.add(item);
                        mItemMap.put(catalog, itemList1);
                        mCatalogList.add(catalog);
                    }
                } while (cursor.moveToNext());
            }
            cursor.close();
        }
    }

    private int getTotalSelectedNum() {
        return PicItemHolder.selectList.size();
    }

    private void updateToolbar() {
        int sum = getTotalSelectedNum();
        if (sum == 0) {
            mBtnSend.setEnabled(false);
            mBtnSend.setTextColor(getResources().getColor(color.ko_picsel_toolbar_send_text_disable));
            mBtnSend.setText(string.ko_picsel_toolbar_send);
            mPreviewBtn.setEnabled(false);
            mPreviewBtn.setText(string.ko_picsel_toolbar_preview);
        } else if (sum <= selectMax) {
            mBtnSend.setEnabled(true);
            mBtnSend.setTextColor(getResources().getColor(color.ko_picsel_toolbar_send_text_normal));
            mBtnSend.setText(String.format(getResources().getString(string.ko_picsel_toolbar_send_num), new Object[]{Integer.valueOf(sum), Integer.valueOf(selectMax)}));
            mPreviewBtn.setEnabled(true);
            mPreviewBtn.setText(String.format(getResources().getString(string.ko_picsel_toolbar_preview_num), new Object[]{Integer.valueOf(sum)}));
        }
    }

    private PicItem getItemAt(String catalog, int index) {
        if (!mItemMap.containsKey(catalog)) {
            return null;
        } else {
            int sum = 0;

            for (Iterator i$ = (mItemMap.get(catalog)).iterator(); i$.hasNext(); ++sum) {
                PicItem item = (PicItem) i$.next();
                if (sum == index) {
                    return item;
                }
            }
            return null;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 100:
                if (grantResults[0] == 0) {
                    if (permissions[0].equals(Manifest.permission.READ_EXTERNAL_STORAGE)) {
                        initView();
                    } else if (permissions[0].equals(Manifest.permission.CAMERA)) {
                        requestCamera();
                    }
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        if (PicItemHolder.itemList != null && PicItemHolder.itemList.size() > 0) {
            outState.putParcelableArrayList("ItemList", PicItemHolder.itemList);
        }
        if (PicItemHolder.selectList != null && PicItemHolder.selectList.size() > 0) {
            outState.putStringArrayList("SelectList", PicItemHolder.selectList);
        }
        outState.putString("TakePicturePath", savePath);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void finish() {
        PicItemHolder.itemList = null;
        PicItemHolder.selectList = null;
        AlbumBitmapCacheHelper.getInstance().unInit();
        super.finish();
    }

    public static class PicItemHolder {
        static ArrayList<PicItem> itemList;
        static ArrayList<String> selectList;
    }

    public static class SelectBox extends ImageView {
        private boolean mIsChecked;

        public SelectBox(Context context, AttributeSet attrs) {
            super(context, attrs);
            setImageResource(drawable.ko_select_check_nor);
        }

        public void setChecked(boolean check) {
            mIsChecked = check;
            setImageResource(mIsChecked ? drawable.ko_select_check_sel : drawable.ko_select_check_nor);
        }

        public boolean getChecked() {
            return mIsChecked;
        }
    }

    public static class PreviewBtn extends LinearLayout {
        private TextView mText;

        public PreviewBtn(Context context, AttributeSet attrs) {
            super(context, attrs);
        }

        public void init(Activity root) {
            mText = (TextView) root.findViewById(id.preview_text);
        }

        public void setText(int id) {
            mText.setText(id);
        }

        public void setText(String text) {
            mText.setText(text);
        }

        public void setEnabled(boolean enabled) {
            super.setEnabled(enabled);
            int color = enabled ? R.color.ko_picsel_toolbar_send_text_normal : R.color.ko_picsel_toolbar_send_text_disable;
            mText.setTextColor(getResources().getColor(color));
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            if (isEnabled()) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        mText.setVisibility(INVISIBLE);
                        break;
                    case MotionEvent.ACTION_UP:
                        mText.setVisibility(VISIBLE);
                        break;
                    default:
                        break;
                }
            }
            return super.onTouchEvent(event);
        }
    }

    public static class PicTypeBtn extends LinearLayout {
        TextView mText;

        public PicTypeBtn(Context context, AttributeSet attrs) {
            super(context, attrs);
        }

        public void init(Activity root) {
            mText = (TextView) root.findViewById(id.type_text);
        }

        public void setText(String text) {
            mText.setText(text);
        }

        public void setTextColor(int color) {
            mText.setTextColor(color);
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            if (isEnabled()) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        mText.setVisibility(INVISIBLE);
                        break;
                    case MotionEvent.ACTION_UP:
                        mText.setVisibility(VISIBLE);
                        break;
                    default:
                        break;
                }
            }
            return super.onTouchEvent(event);
        }
    }

    public static class PicItem implements Parcelable {

        String uri;
        public static final Creator CREATOR = new Creator() {
            public PicItem createFromParcel(Parcel source) {
                return new PicItem(source);
            }

            public PicItem[] newArray(int size) {
                return new PicItem[size];
            }
        };

        @Override
        public int describeContents() {
            return 0;
        }

        PicItem() {
        }

        PicItem(Parcel in) {
            uri = ParcelUtils.readFromParcel(in);
        }

        @Override
        public void writeToParcel(Parcel dest, int flags) {
            ParcelUtils.writeToParcel(dest, uri);
        }
    }

    private class CatalogAdapter extends BaseAdapter {
        private LayoutInflater mInflater = getLayoutInflater();

        @Override
        public int getCount() {
            return mItemMap.size() + 1;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return (long) position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            CatalogAdapter.ViewHolder holder;
            if (convertView == null) {
                view = mInflater.inflate(layout.ko_picsel_catalog_listview, parent, false);
                holder = new CatalogAdapter.ViewHolder();
                holder.image = (ImageView) view.findViewById(id.image);
                holder.name = (TextView) view.findViewById(id.name);
                holder.number = (TextView) view.findViewById(id.number);
                holder.selected = (ImageView) view.findViewById(id.selected);
                view.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            String path;
            if (holder.image.getTag() != null) {
                path = (String) holder.image.getTag();
                AlbumBitmapCacheHelper.getInstance().removePathFromShowlist(path);
            }

            int num = 0;
            boolean showSelected;
            String name;
            Bitmap bitmap;
            BitmapDrawable bd;
            if (position == 0) {
                if (mItemMap.size() == 0) {
                    holder.image.setImageResource(drawable.ko_picsel_empty_pic);
                } else {
                    path = ((PicItem) ((List) mItemMap.get(mCatalogList.get(0))).get(0)).uri;
                    AlbumBitmapCacheHelper.getInstance().addPathToShowlist(path);
                    holder.image.setTag(path);
                    bitmap = AlbumBitmapCacheHelper.getInstance().getBitmap(path, perWidth, perWidth, new ILoadImageCallback() {
                        public void onLoadImageCallBack(Bitmap bitmap, String path1, Object... objects) {
                            if (bitmap != null) {
                                BitmapDrawable bd = new BitmapDrawable(getResources(), bitmap);
                                View v = mGridView.findViewWithTag(path1);
                                if (v != null) {
                                    v.setBackgroundDrawable(bd);
                                    CatalogAdapter.this.notifyDataSetChanged();
                                }

                            }
                        }
                    }, new Object[]{Integer.valueOf(position)});
                    if (bitmap != null) {
                        bd = new BitmapDrawable(getResources(), bitmap);
                        holder.image.setBackgroundDrawable(bd);
                    } else {
                        holder.image.setBackgroundResource(drawable.ko_grid_image_default);
                    }
                }

                name = getResources().getString(string.ko_picsel_catalog_allpic);
                holder.number.setVisibility(View.GONE);
                showSelected = mCurrentCatalog.isEmpty();
            } else {
                path = ((PicItem) ((List) mItemMap.get(mCatalogList.get(position - 1))).get(0)).uri;
                name = mCatalogList.get(position - 1);
                num = ((List) mItemMap.get(mCatalogList.get(position - 1))).size();
                holder.number.setVisibility(View.VISIBLE);
                showSelected = name.equals(mCurrentCatalog);
                AlbumBitmapCacheHelper.getInstance().addPathToShowlist(path);
                holder.image.setTag(path);
                bitmap = AlbumBitmapCacheHelper.getInstance().getBitmap(path, perWidth, perWidth, new ILoadImageCallback() {
                    public void onLoadImageCallBack(Bitmap bitmap, String path1, Object... objects) {
                        if (bitmap != null) {
                            BitmapDrawable bd = new BitmapDrawable(getResources(), bitmap);
                            View v = mGridView.findViewWithTag(path1);
                            if (v != null) {
                                v.setBackgroundDrawable(bd);
                                CatalogAdapter.this.notifyDataSetChanged();
                            }

                        }
                    }
                }, new Object[]{Integer.valueOf(position)});
                if (bitmap != null) {
                    bd = new BitmapDrawable(getResources(), bitmap);
                    holder.image.setBackgroundDrawable(bd);
                } else {
                    holder.image.setBackgroundResource(drawable.ko_grid_image_default);
                }
            }

            holder.name.setText(name);
            holder.number.setText(String.format(getResources().getString(string.ko_picsel_catalog_number), new Object[]{Integer.valueOf(num)}));
            holder.selected.setVisibility(showSelected ? View.VISIBLE : View.INVISIBLE);
            return view;
        }

        private class ViewHolder {
            ImageView image;
            TextView name;
            TextView number;
            ImageView selected;
        }
    }

    private class GridViewAdapter extends BaseAdapter {
        private LayoutInflater mInflater = getLayoutInflater();

        @Override
        public int getCount() {
            int sum = isTakePhoto ? 1 : 0;
            String key;
            if (mCurrentCatalog.isEmpty()) {
                for (Iterator i$ = mItemMap.keySet().iterator(); i$.hasNext(); sum += ((List) mItemMap.get(key)).size()) {
                    key = (String) i$.next();
                }
            } else {
                sum += ((List) mItemMap.get(mCurrentCatalog)).size();
            }
            return sum;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return (long) position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            if (position == 0 && isTakePhoto) {
                View item1 = mInflater.inflate(layout.ko_picsel_grid_camera, parent, false);
                ImageButton view1 = (ImageButton) item1.findViewById(id.camera_mask);
                view1.setOnClickListener(new OnClickListener() {
                    public void onClick(View v) {
                        requestCamera();
                    }
                });
                return item1;
            } else {
                final PicItem item;
                if (mCurrentCatalog.isEmpty()) {
                    item = mAllItemList.get(isTakePhoto ? position - 1 : position);
                } else {
                    item = getItemAt(mCurrentCatalog, isTakePhoto ? position - 1 : position);
                }

                View view = convertView;
                final ViewHolder holder;
                if (convertView != null && convertView.getTag() != null) {
                    holder = (ViewHolder) convertView.getTag();
                } else {
                    view = mInflater.inflate(R.layout.ko_picsel_grid_item, parent, false);
                    holder = new ViewHolder();
                    holder.image = (ImageView) view.findViewById(id.image);
                    holder.mask = view.findViewById(id.mask);
                    holder.checkBox = (SelectBox) view.findViewById(id.checkbox);
                    view.setTag(holder);
                }

                String path;
                if (holder.image.getTag() != null) {
                    path = (String) holder.image.getTag();
                    AlbumBitmapCacheHelper.getInstance().removePathFromShowlist(path);
                }
                if (item != null) {
                    path = item.uri;
                    AlbumBitmapCacheHelper.getInstance().addPathToShowlist(path);
                    holder.image.setTag(path);

                    Bitmap bitmap = AlbumBitmapCacheHelper.getInstance().getBitmap(path, perWidth, perWidth, new ILoadImageCallback() {
                        public void onLoadImageCallBack(Bitmap bitmap, String path1, Object... objects) {
                            if (bitmap != null) {
                                BitmapDrawable bd = new BitmapDrawable(getResources(), bitmap);
                                View v = mGridView.findViewWithTag(path1);
                                if (v != null) {
                                    v.setBackgroundDrawable(bd);
                                }

                            }
                        }
                    }, new Object[]{Integer.valueOf(position)});

                    if (bitmap != null) {
                        BitmapDrawable bd = new BitmapDrawable(getResources(), bitmap);
                        holder.image.setBackgroundDrawable(bd);
                    } else {
                        holder.image.setBackgroundResource(drawable.ko_grid_image_default);
                    }

                    boolean selected = PicItemHolder.selectList.contains(item.uri);
                    holder.checkBox.setChecked(selected);

                    if (selected) {
                        holder.mask.setBackgroundColor(getResources().getColor(color.ko_picsel_grid_mask_pressed));
                    } else {
                        holder.mask.setBackgroundDrawable(getResources().getDrawable(drawable.ko_sp_grid_mask));
                    }
                }

                holder.checkBox.setOnClickListener(new OnClickListener() {
                    public void onClick(View v) {
                        if (!holder.checkBox.getChecked() && getTotalSelectedNum() == selectMax) {
                            Toast.makeText(getApplicationContext(),
                                    getResources().getString(string.ko_picsel_selected_max,
                                            new Object[]{Integer.valueOf(selectMax)}), Toast.LENGTH_SHORT).show();
                        } else {
                            boolean selected = !holder.checkBox.getChecked();
                            holder.checkBox.setChecked(selected);
                            if (selected) {
                                PicItemHolder.selectList.add(item.uri);
                                holder.mask.setBackgroundColor(getResources().getColor(color.ko_picsel_grid_mask_pressed));
                            } else {
                                PicItemHolder.selectList.remove(item.uri);
                                holder.mask.setBackgroundDrawable(getResources().getDrawable(drawable.ko_sp_grid_mask));
                            }
                            updateToolbar();
                        }
                    }
                });

                holder.mask.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (usePreview) {
                            PicItemHolder.itemList = new ArrayList<>();
                            if (mCurrentCatalog.isEmpty()) {
                                PicItemHolder.itemList.addAll(mAllItemList);
                            } else {
                                PicItemHolder.itemList.addAll(mItemMap.get(mCurrentCatalog));
                            }

                            Intent intent = new Intent(PictureSelectorActivity.this, PicturePreviewActivity.class);
                            intent.putExtra(SP_PICTURE_SELECTOR_MAX, selectMax);
                            intent.putExtra("index", position - 1);
                            intent.putExtra("sendOrigin", mSendOrigin);
                            startActivityForResult(intent, 0);
                        } else {
                            if (!holder.checkBox.getChecked() && getTotalSelectedNum() == selectMax) {
                                Toast.makeText(getApplicationContext(),
                                        getResources().getString(string.ko_picsel_selected_max,
                                                new Object[]{Integer.valueOf(selectMax)}), Toast.LENGTH_SHORT).show();
                            } else {
                                boolean selected = !holder.checkBox.getChecked();
                                holder.checkBox.setChecked(selected);
                                if (selected) {
                                    PicItemHolder.selectList.add(item.uri);
                                    holder.mask.setBackgroundColor(getResources().getColor(color.ko_picsel_grid_mask_pressed));
                                } else {
                                    PicItemHolder.selectList.add(item.uri);
                                    holder.mask.setBackgroundDrawable(getResources().getDrawable(drawable.ko_sp_grid_mask));
                                }
                                updateToolbar();
                            }
                        }
                    }
                });
                return view;
            }
        }

        private class ViewHolder {
            ImageView image;
            View mask;
            SelectBox checkBox;
        }
    }
}
